package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleConfigService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ApArticleConfigServiceImpl extends ServiceImpl<ApArticleConfigMapper, ApArticleConfig> implements ApArticleConfigService {
    /**
     * 修改文章
     * @param map
     */
    @Override
    public void updateByMap(Map map) {
        Object articleId = map.get("articleId");
        Object enable = map.get("enable");
        boolean isDown = Boolean.TRUE;
        if (enable.equals(1)){
            isDown = Boolean.FALSE;
        }
        //修改文章
        update(Wrappers.<ApArticleConfig>lambdaUpdate().eq(ApArticleConfig::getArticleId,articleId)
                .set(ApArticleConfig::getIsDown,isDown));
        //上架时生成网页
        if (!isDown){
            createHtml(articleId);
        }
        //当下架时删除url
        if (isDown){
            deleteHtml(articleId);
        }
    }

    /**
     * 删除文章
     * @param articleId
     */
    private void deleteHtml(Object articleId) {
        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery()
                .eq(ApArticleContent::getArticleId, articleId));
        ApArticle apArticle = apArticleMapper.selectOne(Wrappers.<ApArticle>lambdaQuery()
                .eq(ApArticle::getId, articleId));
        String url = apArticle.getStaticUrl();
        apArticle.setStaticUrl("");
        apArticleMapper.updateById(apArticle);
        fileStorageService.delete(url);
    }

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;
    @Autowired
    private Configuration configuration;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private ApArticleMapper apArticleMapper;

    /**
     * 生成文章
     */
    private void createHtml(Object articleId){
        //获取文章内容
        try {
            ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, articleId));
            if (apArticleContent != null && StringUtils.isNotBlank(apArticleContent.getContent())){
                //2.文章内容通过freemarker生成html文件
                //生成一个暂存流
                StringWriter out = new StringWriter();
                //导入生成html的模板
                Template template = configuration.getTemplate("article.ftl");
                Map<String, Object> params = new HashMap<>();
                params.put("content", JSONArray.parseArray(apArticleContent.getContent()));
                template.process(params, out);
                //生成流来传输
                InputStream is = new ByteArrayInputStream(out.toString().getBytes());
                //3.把html文件上传到MinIO中
                String path = fileStorageService.uploadHtmlFile("", apArticleContent.getArticleId() + ".html", is);
                //4.修改ap_article表，保存static_url字段
                ApArticle article = new ApArticle();
                article.setId(apArticleContent.getArticleId());
                article.setStaticUrl(path);
                apArticleMapper.updateById(article);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
